$(function() {

	$.post("../query.htm", {
		t : new Date(),
		listId : "SLAVE_ACCOUNT_BALANCE.queryAccount"
	}, function(data) {
		var tbody = $("#tbody");
		var trTemplate = tbody.find("tr");
		trTemplate.remove();
		var row = null;
		for ( var i in data.rows) {
			row = data.rows[i];
			var newTr = trTemplate.clone();
			newTr.find(".subject_name").html(row["subject_name"]);
			newTr.find(".subject_code").html(row["id"]);
			newTr.find(".row_num").html(row["row_num"]);
			newTr.find(".balance").html(row["balance"]);
			newTr.find(".type").html(row["subject_type"] == "A" ? "资产" : "负债");
			newTr.find(".index").html(parseInt(i) + 1);
			tbody.append(newTr);
		}
	}, "json");

	$.post("../query.htm", {
		t : new Date(),
		listId : "SLAVE_ACCOUNT_BALANCE.countBalance"
	}, function(data) {
		$("#balanceResult").html(data.rows[0].balance);
	}, "json");

	$("#btnDoImproveBalance").click(function() {
		$.post("doImproveBalance.htm", {
			t : new Date(),
			balanceString : $("#balanceString").val().trim(),
			remark : $("#remark").val().trim()
		}, function(data) {
			alert(JSON.stringify(data));
		}, "json");
	});

	$.post("../query.htm", {
		t : new Date(),
		listId : "SLAVE_ACCOUNT_BALANCE.balanceList"
	}, function(data) { 
		var templateTr = $("#lastGroupCountTbody").find("tr");
		templateTr.remove();
		for ( var i in data.rows) {
			var row = data.rows[i];
			var newTr = null;
			var existRow = $("#lastGroupCountTbody").find(
					"[date='" + row["date"] + "']");
			if (existRow.length > 0) {
				newTr = existRow;
			} else {
				newTr = templateTr.clone();
				newTr.attr("date", row["date"]);
				$("#lastGroupCountTbody").append(newTr);
				newTr.find(".date").html(row["date"]);
			}
			
			newTr.find(".bank_dr").html(row["bank_dr"]?row["bank_dr"].toFixed(2):"");
			newTr.find(".bank_cr").html(row["bank_cr"]?row["bank_cr"].toFixed(2):"");
			newTr.find(".bank_cash").html(row["bank_cash"]?row["bank_cash"].toFixed(2):"");
			newTr.find(".COST_NEEDPAY").html(row["cost_needpay"]?row["cost_needpay"].toFixed(2):"");
			newTr.find(".COST_NEEDPAY_COUNT").html(row["cost_needpay_count"]);

			newTr.find(".PAYMENT_PRINCIPAL").html(row["payment_principal"]?row["payment_principal"].toFixed(2):"");
			newTr.find(".PAYMENT_PRINCIPAL_COUNT").html(
					row["payment_principal_count"]);

			newTr.find(".COST_PAYED").html(row["cost_payed"]?row["cost_payed"].toFixed(2):"");
			newTr.find(".COST_percent").html(
					row["cost_rate"] ? row["cost_rate"].toFixed(2) + "%" : "-");

			newTr.show();
		}

		$("#lastGroupCountTbody").find("td").dblclick(function() {

		});
	}, "json");

});